package org.yimon.tool.algo.leetcode;

/**
 * @Author yimon.gao
 * @Description 删除排序链表中的重复元素Ⅱ
 * @Date 2024/8/30 上午11:11
 */
public class LeetCode_082_DeleteDuplicates {

    public static void main(String[] args) {
        System.out.println(LeetCode_082_DeleteDuplicates.deleteDuplicates(new ListNode(1, new ListNode(1, new ListNode(2)))));
    }

    public static ListNode deleteDuplicates(ListNode head) {
        //特殊情况判断
        if (head == null || head.next == null) {
            return head;
        }
        //记录链表节点的上一个节点
        ListNode pre = new ListNode(0, head);
        ListNode result = pre;
        //遍历节点，获取不重复的元素作为pre
        while (pre.next != null) {
            ListNode cur = pre.next;
            if (cur.next != null && cur.val == cur.next.val) {//当前元素与下个元素相等的情况需要继续判断
                while (cur.next != null && cur.val == cur.next.val) {//继续判断，获取最后一个相等元素
                    cur = cur.next;
                }
                pre.next = cur.next;//指向不相等元素
            } else {
                pre = cur;//指向不相等元素
            }
        }

        return result.next;

    }

    private static class ListNode {
        int val;
        ListNode next;

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }
    }
}
